<template>
  <div id="urlPictureUpload">
    <a-input-group compact style="margin-bottom: 16px">
      <a-input v-model:value="fileUrl" style="width: calc(100% - 120px)" placeholder="请输入图片地址" />
      <a-button type="primary" :loading="loading" @click="handleUpload" style="width: 120px">上传</a-button>
    </a-input-group>
    <div class="urlPic">
      <img v-if="picture?.url" :src="picture?.url" alt="avatar">
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import {uploadPictureByUrlUsingPost} from "@/api/pictureController";

// 由父组件传入参数
interface Props {
  picture?: API.PictureVO,
  spaceId?: number,
  onSuccess?: (newPicture: API.PictureVO) => void
}

// 存储返回参数的值
const props = defineProps<Props>()

// 图片上传后至后端的请求逻辑
const loading = ref<boolean>(false);
const fileUrl = ref<string>();

/**
 * 上传图片到后端
 * @param file
 */
const handleUpload = async () => {
  loading.value = true;
  try {
    // 得到图片的id，否则空;如果已经有该图片id，则为更新图片操作
    const params: API.PictureUploadRequest = { fileUrl: fileUrl.value }
    if(props.picture) {
      params.id = props.picture.id;
    }
    // 获取空间id
    params.spaceId = props.spaceId;
    // 等待前端有数据后调用后端接口
    const res = await uploadPictureByUrlUsingPost(params);
    // 如果数据存在将图片信息传递给父组件
    if(res.data.code === 0 && res.data.data) {
      message.success('图片上传成功');
      props.onSuccess?.(res.data.data);
    } else {
      message.error('图片上传失败，' + res.data.message);
    }
  } catch (error) {
    message.error('图片上传失败');
  } finally {
    //执行完毕后将loading值设置回来
    loading.value = false;
  }
};
</script>
<style scoped>
#urlPictureUpload {
  width: 100%;
  height: 100%;
  min-height: 152px;
  min-width: 152px;
}
#urlPictureUpload img {
  max-width: 100%;
  max-height: 480px;
}
#urlPictureUpload .urlPic {
  text-align: center;
  margin-bottom: 12px;
}
</style>
